from bases.db import get_slave_model, QueryMaker, get_model, safe_commit, db
from bases.schame import PaginationParams
from models.model import Permission
from schemas.auth_permission import PermissionCreateSchema, PermissionUpdateSchema


class AuthPermissionService:
    def page_query(self, query_params: PaginationParams):
        filter_data = query_params.filter
        sorter_data = query_params.sorter
        page = query_params.current
        limit = query_params.pageSize

        model = get_model(Permission)

        query = model.query
        qm = QueryMaker(query)
        qm.add_filter(filter_data, model)
        qm.add_sorter(sorter_data, model)
        qm.cfg_filter("name", "contain")
        qm.cfg_filter("value", "contain")
        qm.cfg_filter("type", "==")

        query = qm.get_query().order_by(model.id.desc())
        paginate_query = query.paginate(page=page, per_page=limit)
        return paginate_query

    def patch_page_query(self, page_query):
        page_list = [record.to_dict() for record in page_query.items]
        return page_list

    def create(self, data: PermissionCreateSchema):
        model = get_model(Permission)
        op_data = data.dict()
        op_data["name"] = data.name
        op_data["description"] = data.description
        op_data["value"] = data.value
        op_data["type"] = data.type
        record = model(**op_data)
        record.save()
        return safe_commit(db)

    def update(self, record: Permission, data: PermissionUpdateSchema):
        op_data = data.dict()
        op_data["name"] = data.name
        op_data["description"] = data.description
        op_data["value"] = data.value
        op_data["type"] = data.type
        record.update(**op_data)
        return safe_commit(db)

    def delete(self, record: Permission):
        record.delete()
        return safe_commit(db)


PermissionService = AuthPermissionService()
